package com.xyoto.takeawayUser.service.impl;

import com.xyoto.takeawayUser.constant.DataBasesOperationResult;
import com.xyoto.takeawayUser.entity.UserCache;
import com.xyoto.takeawayUser.enums.OrderEnum;
import com.xyoto.takeawayUser.exception.ExceptionUtils;
import com.xyoto.takeawayUser.mapper.OrderMapper;
import com.xyoto.takeawayUser.mapper.ShoppingMapper;
import com.xyoto.takeawayUser.po.ShoppingOffenPO;
import com.xyoto.takeawayUser.po.UserOffenBuyPO;
import com.xyoto.takeawayUser.service.OrderService;
import com.xyoto.takeawayUser.utils.RedisUtils;
import com.xyoto.takeawayUser.utils.Result;
import com.xyoto.takeawayUser.vo.UserOffenBuyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingMapper shoppingMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 查询用户常买列表
     * @return
     */
    @Override
    public Result getRecently() {
        log.info("开始查询用户常买列表~");
        List<UserOffenBuyVO> userOffenBuyVOList = new ArrayList<>();
        UserCache userMessage = redisUtils.getRedisUserMessage(request);
        Integer userId = userMessage.getId();
        System.out.println(userId);
        //根据用户id查询用户常买商品
        List<UserOffenBuyPO> userOffenBuyPoList = orderMapper.getRecently(userId);
        if (userOffenBuyPoList.size() == DataBasesOperationResult.ERROR){
            log.info("查询用户常买列表为空");
            ExceptionUtils.error(OrderEnum.FIND_USER_OFFEN_BUY_FAILED);
        }

        for (UserOffenBuyPO userOffenBuyPo : userOffenBuyPoList) {
            UserOffenBuyVO userOffenBuyVo = new UserOffenBuyVO();
            BeanUtils.copyProperties(userOffenBuyPo, userOffenBuyVo);
            ShoppingOffenPO shoppingOffenPo = shoppingMapper.getShoppingInfo(userOffenBuyPo.getShoppingId());
            userOffenBuyVo.setShoppingOffenPo(shoppingOffenPo);

            userOffenBuyVOList.add(userOffenBuyVo);
        }
        log.info("查询用户常买列表成功");
        return Result.success(userOffenBuyVOList);
    }
}
